import {
  getJobGroupByPage,
  createJobGroupByPage,
  updateJobGroupByPage,
  queryByIdJobGroup,
  deleteJobGroupByPage,
  testAddressConnect
} from '@/api/actuatorManagement';
import { state } from './actuatorState';
import { Message } from 'element-ui';

const debounce = function(fn, delay) {
  let time = null;
  return function(...args) {
    if (time) {
      clearTimeout(time);
    }
    time = setTimeout(() => {
      fn(...args);
    }, delay);
  };
};

const dealResponse = res => {
  if (res.success) {
    Message.success(res.message);
    return Promise.resolve(true);
  } else {
    return Promise.reject();
  }
};

const testConnect = function(address) {
  return testAddressConnect({ address }).then(res => {
    if (res.success) {
      return Promise.resolve(res.data);
    } else {
      return Promise.reject();
    }
  });
};

const getTableData = debounce(function(receiver) {
  const requestData = { pageIndex: receiver.currentPage - 1, pageSize: receiver.pageSize };
  state.table.loading = true;
  return getJobGroupByPage(requestData).then(res => {
    state.table.loading = false;
    if (res.success && Array.isArray(res.data)) {
      res.data.forEach((item, index) => {
        item.idd = index;
        item.isDelLoading = false;
      });
      state.table.data = res.data;
      state.total = res.total;
    }
  });
}, 500);

export const updataTable = async function(data) {
  const testResult = await testConnect(data.addressList);
  if (testResult) {
    return updateJobGroupByPage(data).then(res => {
      return dealResponse(res);
    });
  } else {
    Message.error('连接机器地址失败');
    return Promise.reject();
  }
};

export const createTable = async function(data) {
  const testResult = await testConnect(data.addressList);
  if (testResult) {
    return createJobGroupByPage(data).then(res => {
      return dealResponse(res);
    });
  } else {
    Message.error('连接机器地址失败');
    return Promise.reject();
  }
};

// 查询执行器下是否有任务
export const checkTask = function(id) {
  return queryByIdJobGroup({ jobGroupId: id }).then(res => {
    if (res.success && Array.isArray(res.data)) {
      return Promise.resolve(res.data.length !== 0);
    } else {
      return Promise.reject();
    }
  });
};

// 删除
export const deleteTable = function({ id }) {
  return deleteJobGroupByPage({ id }).then(res => {
    console.log(res);
    if (res.success) {
      Message.success(res.message);
      state.total = state.total - 1;
      return Promise.resolve(true);
    } else {
      return Promise.resolve(false);
    }
  });
};

const initPage = function() {
  setTimeout(() => {
    getTableData(state);
  });
};

initPage();

export const triggerEventMap = {
  currentPage: getTableData
};
